<template>
    <div class="second-step">
        <el-form :model="ruleForm2" :rules="rules2" ref="ruleForm2" label-width="160px" class="demo-ruleForm">
            <h3>跟投金额信息</h3>
            <div class="flex-content">
                <el-form-item label="合作模式：" prop="modeId">
                    <el-select v-model="ruleForm2.modeId" placeholder="请选择合作模式" :disabled="true">
                        <el-option v-for="(item,index) in modalOptions" :key="index" :label="item" :value="index"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="总投入金额：" prop="totalAmount">
                    <el-input v-model="ruleForm2.totalAmount" class="w-200"></el-input>
                    元
                </el-form-item>
            </div>
            <div class="flex-content">
                <el-form-item label="预计利润率：" prop="profitPercent">
                    <el-input v-model="ruleForm2.profitPercent" class="w-200"></el-input>
                    %
                </el-form-item>
                <div></div>
            </div>
        </el-form>
        <hr>
        <h3>绑定标准及规则</h3>
        <div style="margin-bottom: 10px;" v-for="(item, index) in dialogTitle" :key="index">
            <el-button size="small" @click="bindStandard(index)">绑定跟投{{item}}</el-button>
            <span v-if="bindStandardInfo[index].id">已绑定跟投{{item}} <a class="handleA" href="javascript:" @click="showBindStandardInfo(index)">《{{bindStandardInfo[index].name}}》</a></span>
        </div>
        <el-dialog :title="'选择跟投'+ dialogTitle[tableActive]" width="1000px" :visible.sync="outerVisible">
            <div class="mb20">
                {{dialogSearchTitle[tableActive]}}：
                <el-input class="w-260" v-model="dialogSearchParams[tableActive]" :placeholder="'请输入'+dialogSearchTitle[tableActive]"></el-input>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button @click="onClear">重置</el-button>
            </div>
            <!--管控标准-->
            <el-table
                    :data="tableData"
                    ref="singleTable0"
                    v-if="tableActive === 0"
                    class="second-step-table"
                    border
                    stripe
                    highlight-current-row
                    @current-change="selectedCurrentRow"
                    style="width: 100%">
                <el-table-column :key="Math.random()" align="center" type="index" label="序号" width="50"></el-table-column>
                <el-table-column :key="Math.random()" align="center" label="" width="50">
                    <template slot-scope="scope">
                        <el-radio v-model="bindStandardValue[tableActive]" :label="scope.row"></el-radio>
                    </template>
                </el-table-column>
                <el-table-column :key="Math.random()" align="center" prop="name" label="标准名称"></el-table-column>
                <el-table-column :key="Math.random()" align="center" prop="lineCollaborat" label="合作模式">
                    <template slot-scope="scope">{{modalOptions[scope.row.lineCollaborat]}}</template>
                </el-table-column>
                <el-table-column :key="Math.random()" align="center" label="跟投比例">
                    <template slot-scope="scope"><a href="javascript:" @click="viewInner(scope.row)">查看</a></template>
                </el-table-column>
                <el-table-column :key="Math.random()" align="center" prop="inNumber" label="版本号"></el-table-column>
                <el-table-column :key="Math.random()" align="center" prop="updateName" label="更新人"></el-table-column>
                <el-table-column :key="Math.random()" align="center" prop="updateTime" width="180" label="更新时间"></el-table-column>
            </el-table>
            <!--分配规则-->
            <el-table
                    :data="tableData"
                    ref="singleTable1"
                    v-else-if="tableActive === 1"
                    class="second-step-table"
                    border
                    stripe
                    highlight-current-row
                    @current-change="selectedCurrentRow"
                    style="width: 100%">
                <el-table-column :key="Math.random()" align="center" type="index" label="序号" width="50"></el-table-column>
                <el-table-column :key="Math.random()" align="center" label="" width="50">
                    <template slot-scope="scope">
                        <el-radio v-model="bindStandardValue[tableActive]" :label="scope.row"></el-radio>
                    </template>
                </el-table-column>
                <el-table-column :key="Math.random()" align="center" label="规则名称" prop="name"></el-table-column>
                <el-table-column :key="Math.random()" align="center" label="定向分配占比(%）" width="150" prop="directionalProportion"></el-table-column>
                <el-table-column :key="Math.random()" align="center" label="募集分配占比(%）" width="150" prop="raiseProportion"></el-table-column>
                <el-table-column :key="Math.random()" align="center" label="分配方案">
                    <template slot-scope="scope"><a href="javascript:" @click="viewInner(scope.row)">查看</a></template>
                </el-table-column>
                <el-table-column :key="Math.random()" align="center" label="更新人" prop="updateUsername"></el-table-column>
                <el-table-column :key="Math.random()" align="center" prop="updateTime" width="180" label="更新时间"></el-table-column>

            </el-table>
            <!--分红规则-->
            <el-table
                    :data="tableData"
                    ref="singleTable2"
                    v-else-if="tableActive === 2"
                    class="second-step-table"
                    border
                    stripe
                    highlight-current-row
                    @current-change="selectedCurrentRow"
                    style="width: 100%">
                <el-table-column :key="Math.random()" align="center" type="index" label="序号" width="50"></el-table-column>
                <el-table-column :key="Math.random()" align="center" label="" width="50">
                    <template slot-scope="scope">
                        <el-radio v-model="bindStandardValue[tableActive]" :label="scope.row"></el-radio>
                    </template>
                </el-table-column>
                <el-table-column :key="Math.random()" align="center" label="规则名称" prop="name"></el-table-column>
                <el-table-column :key="Math.random()" align="center" label="计算类型" width="150" prop="type">
                    <template slot-scope="scope">
                        {{scope.row.type === 1? '利润率':'利润额'}}
                    </template>
                </el-table-column>
                <el-table-column :key="Math.random()" align="center" label="区间设置">
                    <template slot-scope="scope"><a href="javascript:" @click="viewInner(scope.row)">查看</a></template>
                </el-table-column>
                <el-table-column :key="Math.random()" align="center" label="更新人" prop="updateUsername"></el-table-column>
                <el-table-column :key="Math.random()" align="center" prop="updateTime" width="180" label="更新时间"></el-table-column>

            </el-table>
            <el-pagination
                    layout="total, sizes, prev, pager, next"
                    style="margin-top:30px"
                    :current-page.sync="tableConfig[tableActive].pageNum"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="tableConfig[tableActive].pageSize"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :total="tableConfig[tableActive].totalSize">
            </el-pagination>
            <div slot="footer" class="dialog-footer">
                <el-button @click="outerVisible = false">关 闭</el-button>
                <el-button type="primary" @click="outerDialogSelected">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog
                width="1000px"
                :title="'查看跟投' + dialogTitle[tableActive] + ' ' + dialogInnerTitle[tableActive]"
                :visible.sync="innerVisible"
                append-to-body>
            <scale-table v-if="tableActive === 0" :tableData="innerTableData"></scale-table>
            <el-table :data="innerTableData"
                      border
                      v-else-if="tableActive === 1"
                      :span-method="objectSpanMethod"
                      :summary-method="getSummaries"
                      show-summary
            >
                <el-table-column :key="Math.random()" type="index" prop="type" label="序号" width="50" align="center"></el-table-column>
                <el-table-column :key="Math.random()" label="业务线" prop="businessName" align="center">
                </el-table-column>
                <el-table-column :key="Math.random()" label="占比（业务线）" prop="businessProportion" align="center">
                </el-table-column>
                <el-table-column :key="Math.random()" label="比例（部门）%" prop="departmentProportion" align="center">
                    <template slot-scope="scope">{{scope.row.departmentProportion?(scope.row.departmentProportion +
                        "%"):'-'}}
                    </template>
                </el-table-column>
                <el-table-column :key="Math.random()" label="部门" prop="departmentName" align="center">
                    <template slot-scope="scope">{{scope.row.departmentName?scope.row.departmentName:'-'}}</template>
                </el-table-column>
                <el-table-column :key="Math.random()" label="职级" prop="rankName" align="center">
                    <template slot-scope="scope">{{scope.row.rankName?scope.row.rankName:'-'}}</template>
                </el-table-column>
                <el-table-column :key="Math.random()" label="比例（职级）%" prop="rankProportion" align="center">
                    <template slot-scope="scope">{{scope.row.rankProportion?(scope.row.rankProportion + "%"):'-'}}
                    </template>
                </el-table-column>
                <el-table-column :key="Math.random()" label="绝对值（职级）%" prop="rankMagnitude" align="center">
                    <template slot-scope="scope">{{scope.row.rankMagnitude?(scope.row.rankMagnitude + "%"):'-'}}
                    </template>
                </el-table-column>
            </el-table>
            <el-table v-else-if="tableActive === 2" :data="innerTableData" border>
                <el-table-column :key="Math.random()" label="利润计算区间" :formatter="initInterval" prop="profitBegin" align="center">
                </el-table-column>
                <el-table-column :key="Math.random()" label="利润分配" prop="profitProportion" align="center">
                    <template slot-scope="scope">
                        {{scope.row.profitProportion}}{{infoBase.dividendUnit === 1 ? '%' :'元'}}
                    </template>
                </el-table-column>
                <el-table-column :key="Math.random()" label="激励基数" prop="profitBase" align="center">
                    <template slot-scope="scope">
                        {{scope.row.profitBase === 1 ? '营收业绩' : ''}}
                    </template>
                </el-table-column>
                <el-table-column :key="Math.random()" label="激励分配" prop="distributionProportion" align="center">
                    <template slot-scope="scope">
                        {{scope.row.distributionProportion}}{{infoBase.dividendUnit === 1 ? '%' : '元'}}
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
    import api from '@/api/apiPath'
    import scaleTable from "../../../standardManage/followUpControl/scaleTable"

    export default {
        name: "secondStep",
        props: ['businessModeCode', 'renderData2'],
        watch: {
            businessModeCode() {
                this.ruleForm2.modeId = this.businessModeCode
            },
            renderData2() {
                if (this.renderData2.profitPercent) {
                    this.ruleForm2.totalAmount = this.renderData2.totalAmount;
                    this.ruleForm2.profitPercent = this.renderData2.profitPercent;
                    this.formatList(this.renderData2.bindStandardInfo)
                }
            }
        },
        data() {
            let numberFormat = (rule, value, callback) => {
                let reg = /^(0|[1-9]\d*)(\s|$|\.\d{1,2}\b)$/g;
                if (!reg.test(value)) {
                    callback(new Error('请输入正数，最多保留小数点后两位!'));
                } else {
                    callback();
                }
            };

            return {
                modalOptions: [
                    "包销模式",
                    "分销模式",
                    "合伙人模式",
                    "加盟模式",
                    "保证金模式"
                ],
                ruleForm2: {
                    modeId: "",
                    totalAmount: "",
                    profitPercent: "",
                },
                rules2: {
                    modeId: [
                        {required: true, message: '请选择合作模式', trigger: 'blur'}
                    ],
                    totalAmount: [
                        {required: true, message: '请输入总投入总额', trigger: 'blur'},
                        {validator: numberFormat, trigger: 'blur'}
                    ],
                    profitPercent: [
                        {required: true, message: '请输入预计利润率', trigger: 'blur'},
                        {validator: numberFormat, trigger: 'blur'}
                    ],
                },
                outerVisible: false,
                innerVisible: false,
                tableActive: 0,
                tableData: [],
                tableConfig: [
                    {
                        pageNum: 1,
                        pageSize: 10,
                        totalSize: 10,
                    },
                    {
                        pageNum: 1,
                        pageSize: 10,
                        totalSize: 10,
                    },
                    {
                        pageNum: 1,
                        pageSize: 10,
                        totalSize: 10,
                    }
                ],
                dialogSearchParams: [
                    "",
                    "",
                    "",
                ],
                dialogSearchTitle: [
                    "标准名称",
                    "分配规则",
                    "分红规则",
                ],
                dialogTitle: ['管控标准', '分配规则', '分红规则'],
                dialogInnerTitle: ['比例区间', '分配方案', '结算区间'],
                bindStandardValue: [
                    {},
                    {},
                    {},
                ],
                bindStandardInfo: [
                    {},
                    {},
                    {}
                ],   //最终所有选择的标准存放在这个变量
                innerTableData: [],
                tableListRequest: [
                    api.selectInvestmentNormVoteForProject,
                    api.DISTRIBUTIONRULELIST,
                    api.SHAREPAGELIST,
                ],
                infoBase: "",
                spanArr: [],

                /*其它页面使用的数据辅助变量*/
                otherPageUse: {
                    thirdMoney: 0,      // 第三步使用的跟投金额
                    thirdScale: 0,      // 第三步使用的募集比例和判断是否跳过第三步
                    fourthRuleId: 0,    // 第四步使用的跟投分配规则ID
                    fourthJudgeJump: 0, // 第四步使用判断是否跳过第三步
                },
            }
        },
        created() {

        },
        methods: {
            formatList(renderData2) {
                this.bindStandardInfo = [
                    {
                        name: renderData2[0].vote.name,
                        id: renderData2[0].vote.id,
                        moneys: renderData2[0].voteMoneys,
                        lineCollaborat: renderData2[0].vote.lineCollaborat
                    },
                    renderData2[1],
                    {
                        name: renderData2[2].shareOut.name,
                        id: renderData2[2].shareOut.id,
                    }
                ]
            },


            // 判断总投入金额是否在跟投管控标准的区间内
            judgeMoneyIsInInterval() {
                let currentTotalMoney = this.ruleForm2.totalAmount;
                let moneys = this.bindStandardInfo[0].moneys;

                console.log(this.bindStandardInfo[0]);
                let isInInterval = false;
                for (let i = 0; i < moneys.length; i++) {
                    let money = moneys[i];
                    for (let j = 0; j < money.rows.length; j++) {
                        let item = money.rows[j];
                        if (item.inRooted === 3) {
                            let resJudgeCondition = false;
                            if (money.inMax) {
                                resJudgeCondition = currentTotalMoney >= money.inMini && currentTotalMoney < money.inMax
                            } else {
                                resJudgeCondition = currentTotalMoney >= money.inMini
                            }
                            if (resJudgeCondition) {
                                this.otherPageUse.thirdMoney = currentTotalMoney * item.inLeaf / 100;
                                isInInterval = true;
                                break;
                            }
                        }
                    }
                }
                if (!isInInterval) {
                    this.$message({
                        message: '总投入金额不在该标准投入金额区间内，请重新选择标准！',
                        type: 'warning'
                    });
                    this.otherPageUse.thirdMoney = 0;
                }
                return isInInterval;
            },
            onSearch() {
                this.tableConfig[this.tableActive].pageNum = 1;
                this.getTableList();
            },
            onClear() {
                this.$set(this.dialogSearchParams, this.tableActive, '');
            },
            bindStandard(index) {
                this.tableActive = index;
                this.innerTableData = [];
                this.tableConfig[this.tableActive].pageNum = 1;
                this.$set(this.dialogSearchParams, this.tableActive, '');
                this.getTableList()
            },
            showBindStandardInfo(index) {
                this.tableActive = index;
                this.viewInner(this.bindStandardInfo[index])
            },
            handleSizeChange(size) {
                this.tableConfig[this.tableActive].pageSize = size;
                this.getTableList()
            },
            handleCurrentChange(page) {
                this.tableConfig[this.tableActive].pageNum = page;
                this.getTableList()
            },
            selectedCurrentRow(val) {
                if (val) {
                    this.bindStandardValue[this.tableActive] = val
                }
            },
            outerDialogSelected() {
                if (this.bindStandardValue[this.tableActive].id) {
                    this.outerVisible = false;
                    this.bindStandardInfo[this.tableActive] = this.bindStandardValue[this.tableActive];
                } else {
                    this.$message({
                        message: '请选择跟投' + this.dialogTitle[this.tableActive],
                        type: 'warning'
                    });
                }
            },
            getTableList() {
                let params = {
                    name: this.dialogSearchParams[this.tableActive],
                    pageNum: this.tableConfig[this.tableActive].pageNum,
                    pageSize: this.tableConfig[this.tableActive].pageSize,
                }
                if (this.tableActive === 0) {
                    //params.inApplication = 1
                    params.lineCollaborat = this.ruleForm2.modeId
                } else {
                    params.status = 1
                }

                this.axios.post(this.tableListRequest[this.tableActive], params).then((res) => {
                    this.tableData = res.data.data.list;
                    this.tableConfig[this.tableActive].totalSize = res.data.data.total;
                    this.outerVisible = true;
                    if (this.bindStandardInfo[this.tableActive].id) {
                        setTimeout(() => {
                            this.$refs['singleTable' + this.tableActive].setCurrentRow(
                                this.tableData.find(item => {
                                    if (item.id === this.bindStandardInfo[this.tableActive].id) {
                                        return item
                                    }
                                })
                            );
                        }, 30)
                    }
                })
            },
            viewInner(row) {
                if (this.tableActive === 0) {
                    this.innerTableData = row.moneys;
                    this.innerVisible = true;
                } else if (this.tableActive === 1) {
                    this.axios.get(api.DISTRIBUTTIONVIEW + row.id).then((res) => {
                        if (res.data.code === 200) {
                            this.innerTableData = res.data.data.distributionDetailList;
                            this.rowspan(1, 'businessId');
                            this.rowspan(2, 'businessId');
                            this.rowspan(3, 'departId');
                            this.rowspan(4, 'departId');
                            this.innerVisible = true;
                        }
                    })
                } else if (this.tableActive === 2) {
                    this.axios.get(api.INVESTSECTIONS + '/' + row.id).then((res) => {
                        if (res.data.code === 200) {
                            this.innerTableData = res.data.data.shareDateail;
                            this.infoBase = res.data.data.shareOut;
                            this.innerVisible = true;
                        }
                    })
                }
            },
            /* 分红规则查看弹框使用  =>静静*/
            initInterval(row) {
                let str = ''
                if (!row.profitBegin) {
                    str = '<' + row.profitEnd + (this.infoBase.type === 1 ? '%' : '元')
                } else if (row.profitBegin && row.profitEnd) {
                    str = row.profitBegin + (this.infoBase.type === 1 ? '%' : '元') + '(含) -' + row.profitEnd + (this.infoBase.type === 1 ? '%' : '元') + '(不含）'
                } else if (!row.profitEnd) {
                    str = '≥' + row.profitBegin + (this.infoBase.type === 1 ? '%' : '元')
                }
                return str
            },
            /* 分配规则查看弹框合并表格使用  =>静静*/
            objectSpanMethod({row, column, rowIndex, columnIndex}) {
                for (let i = 1; i < 5; i++) {
                    if (columnIndex === i) {
                        const _row = this.spanArr[i][rowIndex];
                        const _col = _row > 0 ? 1 : 0;
                        return {
                            rowspan: _row,
                            colspan: _col
                        }
                    }
                }
            },
            rowspan(idx, prop) {
                this.spanArr[idx] = [];
                this.position = 0;
                let len = 0;
                this.innerTableData.forEach((item, index) => {
                    if (index === 0) {
                        this.spanArr[idx].push(1);
                        this.position = 0;
                    } else {
                        if (this.innerTableData[index][prop] === this.innerTableData[index - 1][prop]) {
                            this.spanArr[idx][this.position] += 1;//有相同项
                            this.spanArr[idx].push(0); // 名称相同后往数组里面加一项0
                        } else {
                            this.spanArr[idx].push(1);//同列的前后两行单元格不相同
                            this.position = index;
                        }
                    }
                })
            },
            getSummaries(param) {
                return ["合计", , 100, , , , , 100];
            },
            isCanGoNextStep() {
                return new Promise((resolve) => {

                    if (this.ruleForm2.modeId !== this.bindStandardInfo[0].lineCollaborat) {
                        this.$message({
                            message: '项目合作模式与跟投管控标准不匹配，请重新编辑',
                            type: 'warning'
                        });
                        resolve(false);
                        return false;
                    }

                    this.$refs.ruleForm2.validate((valid) => {
                        if (valid) {
                            for (let i = 0; i < this.bindStandardInfo.length; i++) {
                                let item = this.bindStandardInfo[i];
                                if (!item.id) {
                                    this.$message({
                                        message: '请选择跟投' + this.dialogTitle[i],
                                        type: 'warning'
                                    });
                                    resolve(false);
                                    return false;
                                }
                            }
                            this.otherPageUse.thirdScale = this.bindStandardInfo[1].raiseProportion;
                            this.otherPageUse.fourthJudgeJump = this.bindStandardInfo[1].directionalProportion;
                            this.otherPageUse.fourthRuleId = this.bindStandardInfo[1].id;

                            this.axios.post(api.saveProjectDetailInfocheckRules, {
                                projectStandard: [
                                    {
                                        standardName: this.bindStandardInfo[0].name,
                                        standardId: this.bindStandardInfo[0].id,
                                        standardType: 1
                                    },
                                    {
                                        standardName: this.bindStandardInfo[1].name,
                                        standardId: this.bindStandardInfo[1].id,
                                        standardType: 2
                                    },
                                    {
                                        standardName: this.bindStandardInfo[2].name,
                                        standardId: this.bindStandardInfo[2].id,
                                        standardType: 3
                                    }
                                ],
                                investTotalMoney: this.ruleForm2.totalAmount,
                                projectedProfitMargin: this.ruleForm2.profitPercent,
                            }).then((res) => {
                                if (res.data.code === 200) {
                                    resolve(this.judgeMoneyIsInInterval());
                                } else {
                                    resolve(false);
                                }
                            })
                        } else {
                            resolve(false);
                        }
                    });
                })
            }
        },
        components: {
            /* 跟投标准查看弹框使用  =>武武*/
            'scale-table': scaleTable
        },
    }
</script>

<style>
    .second-step .second-step-table .el-radio__label {
        display: none;
    }

    .second-step .handleA {
        text-decoration: none;
    }
</style>
